<?php
class LESSPHP_Plugin_Variables extends LESSPHP_Plugin_Abstract{
	
	protected $_variables = array();
	
	public function apply(SimpleXMLElement $cssXml){
		$this->_applyVariables($cssXml);
	}
	
	protected function _applyVariables(SimpleXMLElement $cssXml, $depth = 0){
		$this->_resetVariables($depth);
		foreach($cssXml->variable as $variable){
			$this->_setVariable((string)$variable['name'], (string)$variable, $depth);
		}
		foreach($cssXml->ruleset as $ruleset){
			$this->_applyVariables($ruleset, $depth + 1);
		}
		if($depth > 0){
			for($i = 0, $c = count($cssXml->property); $i < $c; $i++){
				$property = (string)$cssXml->property[$i];
				if(strpos($property, '@') === false) continue; //Nothing to see here. Move along.
				if(!preg_match_all('/@([A-Z0-9a-z_-]+)/', $property, $results,  PREG_SET_ORDER)) continue;
				foreach ($results as $result){
					$property = str_replace($result[0], $this->_getVariable($result[1], $depth), $property);	
				}
				$cssXml->property[$i] = $property;
			}
		}
	}
	
	protected function _getVariable($name, $depth){
		while($depth >= 0){
			if(isset($this->_variables[$depth][$name])){
				return $this->_variables[$depth][$name];
			}
			$depth--;
		}
		return '';
	}
	
	protected function _setVariable($name, $value, $depth){
		$this->_variables[$depth][$name] = $value;
	}
	
	protected function _resetVariables($depth){
		$this->_variables[$depth] = array();
	}
	
	public function transformCss($css){
		return preg_replace('/@([a-zA-Z0-9-_]+)\\s?:\\s?([^;]*);/', '<variable name="$1">$2</variable>', $css);
	}
	
}